package com.itcast.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itcast.yygh.oss.service.OssService;
import com.itcast.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file) {
        //1.先获取阿里云仓库的连接信息  endpoint  accessKey  仓库的名称
        //endpoint地址
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String ACCESS_KEY_ID =ConstantPropertiesUtil.ACCESS_KEY_ID;
        String ACCESS_KEY_SECRET = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String BUCKET_NAME = ConstantPropertiesUtil.BUCKET_NAME;
        //2.创建oss上传的实例
        try{
            OSS ossClient = new OSSClientBuilder().build(endPoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            //3.处理上传文件名称
                //将file转换流
            InputStream inputStream = file.getInputStream();
            //获取file的name
            String originalFilename = file.getOriginalFilename();
            //把文件名称改成随机字符
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            originalFilename = uuid+originalFilename;
            //在文件名上加上时间戳
            String date = new DateTime().toString("yyyy-MM-dd");
            originalFilename=date+originalFilename;
            //4.进行文件的上传
            ossClient.putObject(BUCKET_NAME,originalFilename,inputStream);
            ossClient.shutdown();
            //5.返回上传后的图片路径
            String url = "https://"+BUCKET_NAME+"."+endPoint+"/"+originalFilename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
